package com.baosight.risk.service.api.impl;

import com.baosight.risk.api.api.HuaBaoService;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.api.HuaBaoMapper;
import com.baosight.risk.mapper.zbaa.ZbaaTargetMapper;
import com.baosight.risk.mapper.zbaa.ZbaaTargetValueMapper;
import com.baosight.risk.service.zbaa.entity.ZbaaTarget;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetValue;
import com.baosight.risk.service.zbaa.vo.ZbaaTargetHomeIndexVO;
import com.baosight.risk.service.zbaa.vo.ZbaaTargetValueVO;
import groovy.util.logging.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 侯湘锦
 * @create 2020/09/21 13:45
 */
@Service
@Slf4j
public class HuaBaoServiceImpl implements HuaBaoService {

    @Autowired
    private ZbaaTargetMapper targetMapper;

    @Autowired
    private ZbaaTargetValueMapper targetValueMapper;

    @Resource
    private HuaBaoMapper huaBaoMapper;


    @Override
    public List<ZbaaTargetHomeIndexVO> getHomeIndex() {
        List<ZbaaTargetHomeIndexVO> resultList = new ArrayList<>();

        // 页面上展示的指标targetNo:按顺序写死
        // 社会融资同比增幅，制造业PMI同比增幅,国内生产总值月度GDP，国内汽车销量，房地产当月销量
        // 普氏62%铁矿石指数,CR炼焦煤价格指数,中国粗钢产量,钢铁社会库存总量,供需平衡
        // 指标对应的组织 Wind SSB MySteel
        List<String> targetNoList = new ArrayList<>(Arrays.asList("ZBW0009", "ZBW0034", "ZBW0005", "ZBW0049", "ZBW0236", "ZBW0055", "ZBW0158", "ZBW0059", "ZBW0064", "ZBW0000"));
        List<String> targetPeriodList = new ArrayList<>(Arrays.asList("月", "月", "季", "月", "月", "日", "日", "月", "日", "季"));
        List<String> sysSourceList = new ArrayList<>(Arrays.asList("Y", "Wind", "Wind", "CPCA", "SSB", "Wind", "Bsteel", "Wind", "Bsteel", "G"));
        // 同比上年数据处理，同比为Y，环比N
        List<String> compareList = new ArrayList<>(Arrays.asList("Y", "N", "Y", "Y", "Y", "N", "N", "Y", "N", "Y"));
        for (int i = 0; i < targetNoList.size(); i++) {

            ZbaaTargetHomeIndexVO resultVO = new ZbaaTargetHomeIndexVO();

            // 插入指标定义
            ZbaaTarget zbaaTarget = targetMapper.getTargetByTargetNo(targetNoList.get(i));
            if (zbaaTarget != null) {
                resultVO.setDefinition(zbaaTarget.getTargetDesc());
            }

            // 获取当前指标最新的指标数据
            List<ZbaaTargetValue> targetValueList = huaBaoMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSourceList.get(i), null, null, "2");
            ZbaaTargetValue latestValue = targetValueList.size() > 0 ? targetValueList.get(0) : null;
            ZbaaTargetValue previousValue = targetValueList.size() > 1 ? targetValueList.get(1) : null;

            if (latestValue == null) {
                // 最新指标数据无结果，则全部填-
                resultVO.setValue("-");
                resultVO.setRate("-");
                resultVO.setStatus("-");
                resultVO.setRemark("<br/>当前指标无数据");
                resultVO.setStatisticsTime("-");
                resultList.add(resultVO);
                continue;
            }

            // 判断是否同比，更新previousValue信息。
            String latestPeriod = latestValue.getPeriodNo();
            if (compareList.get(i).equals("Y")) {
                int year = Integer.parseInt(latestPeriod.substring(0, 4)) - 1;
                String perviousPeriodNo = String.valueOf(year) + latestPeriod.substring(4, latestPeriod.length());
                List<ZbaaTargetValue> valueList = huaBaoMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSourceList.get(i),null, perviousPeriodNo, "1");
                previousValue = valueList.size() > 0 ? valueList.get(0) : null;
            }

            if (previousValue == null) {
                // 上一条数据无结果，则填-
                resultVO.setValue(latestValue.getTargetValue());
                resultVO.setRate("-");
                resultVO.setStatus("-");
                resultVO.setSource(latestValue.getSysSourceName());
                resultVO.setCreateTime(latestValue.getCreateTime());
                String remark = "<br/>" + latestPeriod + "数据值：" + latestValue.getTargetValue() + "</br>";
                resultVO.setRemark(remark);
                resultVO.setStatisticsTime(latestPeriod);
                resultList.add(resultVO);
                continue;
            }

            // 常规计算
            double currentData = Double.parseDouble(latestValue.getTargetValue());
            double lastData = Double.parseDouble(previousValue.getTargetValue());

            // 状态为1是上升，0位下降。
            String status = currentData - lastData >= 0 ? "1" : "0";
            String rate = String.valueOf(Math.abs(currentData - lastData) / Math.abs(lastData));
            resultVO.setValue(String.valueOf(currentData));
            resultVO.setRate(rate);
            resultVO.setStatus(status);
            resultVO.setSource(latestValue.getSysSourceName());
            resultVO.setCreateTime(latestValue.getCreateTime());
            String remark = "<br/>" + latestPeriod + "数据值：" + currentData + "</br>";
            remark += previousValue.getPeriodNo() + "数据值：" + lastData;
            resultVO.setRemark(remark);
            resultVO.setStatisticsTime(latestPeriod);
            resultList.add(resultVO);
        }
        System.out.println(resultList);
        return resultList;
    }



    @Override
    public JSONObject getHomeIndexStatus() {
        // 页面上展示的指标targetNo:按顺序写死的
        // 社会融资增速，制造业PMI, GDP增速，汽车销量，房产销量
        List<String> targetNoList = new ArrayList<>(Arrays.asList("ZBW0009", "ZBW0034", "ZBW0005", "ZBW0049", "ZBW0236"));
        List<String> sysSourceList = new ArrayList<>(Arrays.asList("Y", "Wind", "Wind", "CPCA", "SSB"));

        List<String> dataList = new ArrayList<>();
        List<String> remarkList = new ArrayList<>();
        List<String> statusList = new ArrayList<>();
        // 获取当前指标最新的指标数据
        for (int i = 0; i < targetNoList.size(); i++) {
            List<ZbaaTargetValue> targetValueList = huaBaoMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSourceList.get(i), null, null, "1");
            ZbaaTargetValue latestValue = CollectionUtils.isNotEmpty(targetValueList) ? targetValueList.get(0) : new ZbaaTargetValue();
            dataList.add(StringUtils.isEmpty(latestValue.getStabilityName()) ? "" : latestValue.getStabilityName());
            remarkList.add(StringUtils.isEmpty(latestValue.getValuePeriodRange()) ? "" : latestValue.getValuePeriodRange());
            statusList.add(StringUtils.isEmpty(latestValue.getStabilityCode()) ? "" : latestValue.getStabilityCode());

        }
        Map<String, Object> maps = new HashMap<>();
        maps.put("data", dataList);
        maps.put("remark", remarkList);
        maps.put("status", statusList);
        System.out.println(maps);

        return JSONObject.fromObject(maps);
    }


    @Override
    public List<List<ZbaaTargetValueVO>> getHomeIndexDataList() {
        List<List<ZbaaTargetValueVO>> resultList = new ArrayList<>();

        // 页面上展示的指标数据targetNo:按顺序写死
        // 工业生产者出厂价格指数（PPI）,Mysteel钢材综合价格指数, 西本新干线钢材指数,
        // 普氏62%铁矿石指数,CR炼焦煤价格指数,中国粗钢产量,钢铁社会库存总量
        List<String> targetNoList = new ArrayList<>(Arrays.asList("ZBW0033", "ZBW0106", "ZBW0146", "ZBW0055", "ZBW0158", "ZBW0059", "ZBW0064"));
        List<String> targetPeriodList = new ArrayList<>(Arrays.asList("月", "日", "日", "日", "日", "月", "日"));
        List<String> wind = new ArrayList<>(Arrays.asList("Wind"));
        List<String> ssb = new ArrayList<>(Arrays.asList("SSB"));
        List<String> mysteel = new ArrayList<>(Arrays.asList("Mysteel"));
        List<String> bsteel = new ArrayList<>(Arrays.asList("Bsteel"));
        List<List<String>> sysSourceList = new ArrayList<>(Arrays.asList(wind, bsteel, wind, wind, bsteel, wind, bsteel));

        for (int i = 0; i < targetNoList.size(); i++) {
            String targetNo = targetNoList.get(i);
            String period = targetPeriodList.get(i);

            String sysSource = sysSourceList.get(i).get(0);
            // 获取当前指标最新的指标更新时间
            List<ZbaaTargetValue> targetValueList = new ArrayList<>();
            if ("ZBW0106".equals(targetNo)){
                targetValueList = huaBaoMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSource, "BGTA", null, "1");
            }else {
                targetValueList = huaBaoMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSource, null, null, "1");
            }

            ZbaaTargetValue latestValue = targetValueList.size() > 0 ? targetValueList.get(0) : null;
            if (latestValue == null) {
                // 无数据则添加一条对应的空数组记录
                List<ZbaaTargetValueVO> result = new ArrayList<>();
                resultList.add(result);
                continue;
            }

            String endTime = latestValue.getPeriodNo();
            if (targetPeriodList.get(i).equals("月")) {
                endTime = endTime + "01";
            }
            //将endTime格式YYYYMMDD改写成YYYY-MM-DD
            endTime = endTime.substring(0, 4) + "-" + endTime.substring(4, 6) + "-" + endTime.substring(6, 8);

            String interval = "10";
            String startTime = DateUtils.caculateTime(endTime, period, interval);
            List<ZbaaTargetValueVO> result = getHomeValue(targetNo, sysSourceList.get(i), startTime, endTime, period);
            resultList.add(result);
        }
        System.out.println(resultList);
        return resultList;
    }

    public List<ZbaaTargetValueVO> getHomeValue(String targetNo, List<String> sysSourceList, String startTime, String endTime, String period) {

        String start = startTime.replaceAll("-", "");
        String end = endTime.replaceAll("-", "");
        //获取过滤日期范围
        List<String> rangeList = DateUtils.getRangeList(startTime, endTime, period);
        //获取全部单位数据
        List<ZbaaTargetValue> dataResult = new ArrayList<>();
        //区分开ZBW0106 的两种数据
        if ("ZBW0106".equals(targetNo)){
            ArrayList<String> strings = new ArrayList<>();
            strings.add("BGTA");
            dataResult =huaBaoMapper.getValue(targetNo, sysSourceList,strings, start, end);
        }else{
            dataResult =huaBaoMapper.getValue(targetNo, sysSourceList, null, start, end);
        }

        //按照单位分组
        Map<String, List<ZbaaTargetValue>> groupByComp = dataResult.stream().collect(Collectors.groupingBy(ZbaaTargetValue::getSysSource));

        //遍历分组,拼接返还结果
        List<ZbaaTargetValueVO> finalResult = new ArrayList<>();
        for (Map.Entry<String, List<ZbaaTargetValue>> dataEntry : groupByComp.entrySet()) {

            List<ZbaaTargetValue> dataList = dataEntry.getValue();
            //对数据进行后处理（重复的数据周期范围仅取一条，无数据补充0值）
            if (dataResult != null && dataResult.size() != 0) {

                // 判断当前指标是否需要按照工作日处理
                ZbaaTarget zbaaTarget = huaBaoMapper.getTargetByTargetNo(targetNo);
                String isWorkDay = zbaaTarget.getIsWorkDay();

                ZbaaTargetValueVO zbaaTargetValueVO = new ZbaaTargetValueVO();
                zbaaTargetValueVO.setTargetName(dataList.get(0).getTargetName());
                zbaaTargetValueVO.setTargetNo(dataList.get(0).getTargetNo());
                zbaaTargetValueVO.setSource(dataList.get(0).getSysSource());
                zbaaTargetValueVO.setUnit(dataList.get(0).getUnit());
                zbaaTargetValueVO.setCreateTime(dataList.get(0).getCreateTime());
                zbaaTargetValueVO.setDefinition(zbaaTarget.getTargetDesc());
                List<ZbaaTargetValue> zbaaTargetValueList = new ArrayList<>();

                //对数据进行后处理
                for (int i = 0; i < rangeList.size(); i++) {
                    ZbaaTargetValue zbaaTargetValue = new ZbaaTargetValue();
                    zbaaTargetValue.setTargetName(dataList.get(0).getTargetName());
                    zbaaTargetValue.setSysSource(dataList.get(0).getSysSource());
                    zbaaTargetValue.setSysSourceName(dataList.get(0).getSysSourceName());
                    zbaaTargetValue.setUnit(dataList.get(0).getUnit());
                    zbaaTargetValue.setPeriodNo(rangeList.get(i));
                    zbaaTargetValue.setTargetValue("0");

                    // 遍历原数据后赋值
                    String range = rangeList.get(i);
                    List<ZbaaTargetValue> list = dataList.stream().filter(targetValue -> targetValue.getPeriodNo().equals(range)).collect(Collectors.toList());
                    if (list.size() > 0) {
                        // 有数据集则将第一条数据作为真实数据插入
                        zbaaTargetValue.setTargetValue(list.get(0).getTargetValue());
                        zbaaTargetValueList.add(zbaaTargetValue);
                        continue;
                    } else {
                        //  若为工作日则跳过空数据
                        if (isWorkDay.equals("Y") && period.equals("日")) {
                            continue;
                        }
                        // 非工作日则对数据补0
                        zbaaTargetValueList.add(zbaaTargetValue);
                        continue;
                    }
                }
                zbaaTargetValueVO.setDataList(zbaaTargetValueList);
                finalResult.add(zbaaTargetValueVO);
            }
        }
        return finalResult;
    }
}
